package com.phpxiu.app.okhttp.handler;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.google.gson.JsonParseException;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.OKHttpResponseModel;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * @file
 * @brief 自定义封装okhttp请求UI回调
 * @author 吴金洲
 * @note 自定义封装okhttp请求UI回调
 *
 */
public abstract class OKHttpUIHandler<T extends OKHttpResponseModel> extends Handler implements Callback {
    private final static boolean DEBUG=false;
    public final static String TAG="OKHttpUIHandler";
    public final static int SUCCESS=1;//业务成功，数据正常
    public final static int FAILED=0;//请求失败
    public final static int ERR_IO=-1;//IO异常
    public final static int ERR_JSON_PARSE=-2;//json解析错误，非json格式的数据
    public final static int ERR_EMPTY=-3;//空数据
    public Class<T> cls;
    public T model;
    public OKHttpUIHandler(Class<T> cls) {
        this.cls=cls;
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what){
            case SUCCESS:
                onSuccess(msg.obj);
                break;
            case FAILED:
                OKHttpResponseModel failed=(OKHttpResponseModel)msg.obj;
                String err=OKHttp.RESPONSE_ERR.get(failed.getErrorCode());
                onErr(err==null?("Err:"+failed.getErrorCode()):err);
                onCodeErr(failed.getErrorCode(),err);
                break;
            case ERR_IO:
                onErr("request failure!");
                break;
            case ERR_JSON_PARSE:
                onErr("jsonParseException");
                break;
            case ERR_EMPTY:
                onErr("filed is null");
                break;
            default:
                if(msg.obj!=null) {
                    onErr(msg.obj.toString());
                }
                break;
        }
    }


    /***
     * 请求响应失败
     * @param call
     * @param e
     */
    @Override
    public void onFailure(Call call, IOException e) {
        sendEmptyMessage(ERR_IO);
    }

    /**
     * 响应成功
     * @param call
     * @param response
     * @throws java.io.IOException
     */
    @Override
    public void onResponse(Call call, Response response) throws IOException {
        if (response.isSuccessful()) {
            String result = response.body().string();
            if (DEBUG) {
                Log.e(TAG, "解析前数据：" + result);
            }
            OKHttpResponseModel baseModel = null;
            try {
                baseModel = OKHttp.GSON.fromJson(result, OKHttpResponseModel.class);
            } catch (JsonParseException e) {
                sendEmptyMessage(ERR_JSON_PARSE);
                return;
            }
            if (baseModel == null || baseModel.getErrorCode() == null || baseModel.getErrorCode().equals("")) {
                sendEmptyMessage(ERR_EMPTY);
                return;
            }
            if(!baseModel.getErrorCode().equals("0")){
                Message msg =obtainMessage();
                msg.what = FAILED;
                msg.obj = baseModel;
                sendMessage(msg);
                return;
            }
            if (baseModel.getErrorCode().equals("0")) {
                try {
                    model = OKHttp.GSON.fromJson(result, cls);
                    model.setResponseStr(result);
                } catch (JsonParseException e) {
                    sendEmptyMessage(ERR_JSON_PARSE);
                    return;
                }
                Message msg =obtainMessage();
                msg.what = SUCCESS;
                msg.obj = model;
                sendMessage(msg);
                if (DEBUG) {
                    Log.i(TAG, "解析成功数据：" + result);
                }
            }
        } else {
            if (DEBUG&&response!=null) {
                Log.e(TAG, "请求发生未知错误"+response.toString());
            }
        }
    }

    /**
     * 带错误码
     * @param code
     * @param msg
     */
    public void onCodeErr(String code,String msg){

    }

    /**
     * 回收
     * @throws Throwable
     */
    @Override
    protected void finalize() throws Throwable {
        super.finalize();
    }

    public abstract void onSuccess(Object model);

    public abstract void onErr(String errMsg);
}
